import 'package:flutter/material.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/datas/game_item.dart';
import 'package:flutter_syt/datas/game_video_list_item.dart';
import 'package:flutter_syt/datas/venue_item.dart';
import 'package:flutter_syt/domain/games/game_utils/game_utils_controller.dart';
import 'package:flutter_syt/domain/widgets/network_load_image.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/widgets/normal_table.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

@RoutePage(name: "gameLiveList")
class GameLiveListPage extends StatefulWidget {
  bool needBar = true;
  @override
  State<StatefulWidget> createState() {
    return GameLiveListState(S().live, needBar);
  }
}

class GameLiveListState extends State {
  String title;
  bool needBar = true;
  int chooseType = 0;
  int selectedVenue = -1;
  int selectedGame = -1;
  int tempSelected = -1;
  NormalTableViewController _tableController = NormalTableViewController();
  List<VenueItem> venueList = [];
  List<GameDetail> gameList = [];
  GameLiveListState(this.title, this.needBar);

  @override
  void initState() {
    // getData();
    super.initState();
    GameUtilsController.managerCont['6'] = _tableController;
  }

  Widget buildItem(GameVideoListItem item) {
    var role = item.role_exclusive_name;
    return AspectRatio(
      aspectRatio: 355.0 / 200.0,
      // loadNetworkProviderImage
      child: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(12)),
              image: NetworkLoadImage.loadNetworkProviderImage(item.cover),
            ),
          ),
          // NetworkLoadImage.loadNetworkImage(
          //   // CachedNetworkImage(
          //   // imageUrl:
          //   item.cover,
          //   fit: BoxFit.cover,
          //   width: double.infinity,
          //   height: double.infinity,
          //   compressionRatio: 0.2
          // ),
          Positioned.fill(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Container(
                  height: 90,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(12),
                          bottomRight: Radius.circular(12)),
                      gradient: LinearGradient(
                        colors: [
                          Color(0xff131313).withOpacity(0.75),
                          Color(0xff1b1b1b).withOpacity(0.41),
                          Color(0x00242424),
                        ],
                        begin: Alignment.bottomCenter,
                        end: Alignment.topCenter,
                      )),
                ),
              ],
            ),
          ),
          // EditableTextState()
          Positioned.fill(
            child: Column(
              children: [
                if (role.length > 0)
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Container(
                        padding:
                            EdgeInsets.symmetric(horizontal: 10, vertical: 2),
                        decoration: BoxDecoration(
                          color: ThemeColor.primaryColor,
                          borderRadius: BorderRadius.only(
                            bottomLeft: Radius.circular(8),
                            topRight: Radius.circular(8),
                          ),
                        ),
                        child: Text(
                          role,
                          style: TextStyle(
                              fontSize: 11,
                              color: Colors.black,
                              fontWeight: FontWeight.w500),
                        ),
                      ),
                    ],
                  ),
                Spacer(),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 15),
                  child: Row(
                    children: [
                      Container(
                        padding:
                            EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                        decoration: BoxDecoration(
                          color: Color(0xfff54b46),
                          borderRadius: BorderRadius.all(Radius.circular(2)),
                        ),
                        child: Row(
                          children: [
                            RichText(
                              textAlign: TextAlign.left,
                              text: TextSpan(
                                children: [
                                  WidgetSpan(
                                      child: Padding(
                                          padding: EdgeInsets.only(
                                              right: 4, bottom: 2),
                                          child: Image.asset(
                                            "assets/icons/game_event_live.gif",
                                            width: 14,
                                            height: 14,
                                            color: Colors.white,
                                          ))),
                                  TextSpan(
                                    text: S.of(context).live_2,
                                    style: (TextStyle(
                                      fontWeight: FontWeight.w500,
                                      fontSize: 11,
                                      color: Colors.white.withOpacity(0.8),
                                    )),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 15),
                  child: Row(
                    children: [
                      Flexible(
                        child: Text(
                          item.name,
                          style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w500,
                              color: Colors.white,
                              height: 2),
                        ),
                      ),
                    ],
                  ),
                ),
                // padd
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 15),
                  child: Row(
                    // crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Icon(
                        Icons.location_on_outlined,
                        color: Colors.white,
                        size: 12,
                      ),
                      // Expanded(
                      Expanded(
                        child: Text(
                          item.venue.name,
                          maxLines: 2,
                          // overflow: TextOverflow.ellipsis,
                          style: TextStyle(fontSize: 12, color: Colors.white),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  height: 15,
                ),
              ],
            ),
          ),
        ],
      ),
      // ),
    );
  }

  Widget itemWidget(GameVideoListItem item) {
    return GestureDetector(
      child: buildItem(item),
      onTap: ClickUtils.debounce(() {
        if (item.linkType == 1) {
          RouteManager.push(
              context, RoutMapping.gameDetail(item.id, isVideo: true));
        } else {
          RouteManager.push(context, RoutMapping.webDetail(item.h5Url));
        }
        // RouteManager.push(context, item.path);

        //
      }),
    );
  }

  Widget chooseBar() {
    var venueName = S.of(context).Venues2;
    if (selectedVenue != -1 && selectedVenue < venueList.length) {
      venueName = venueList[selectedVenue].name;
    }
    var gameName = S.of(context).Sports3;
    if (selectedGame != -1 && selectedGame < gameList.length) {
      gameName = gameList[selectedGame].discipline_name;
    }
    return Container(
      height: 36,
      child: Row(
        children: [
          Expanded(
            child: GestureDetector(
              onTap: ClickUtils.debounce(() {
                setState(() {
                  tempSelected = selectedVenue;
                  // if (chooseType == 1) {
                  // chooseType = 0;
                  // }
                  chooseType = chooseType == 1 ? 0 : 1;
                  // chooseType = 1;
                });
              }),
              child: Container(
                height: 36,
                margin: EdgeInsets.symmetric(horizontal: 15),
                padding: EdgeInsets.symmetric(horizontal: 5),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Flexible(
                      child: Text(
                        venueName,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 14, fontWeight: FontWeight.w500),
                      ),
                    ),
                    Icon(
                      chooseType == 1
                          ? Icons.keyboard_arrow_up
                          : Icons.keyboard_arrow_down,
                      color: Color(0xff979797),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Expanded(
            child: GestureDetector(
              onTap: ClickUtils.debounce(() {
                setState(() {
                  tempSelected = selectedGame;
                  // chooseType = 2;
                  chooseType = chooseType == 2 ? 0 : 2;
                });
              }),
              child: Container(
                height: 36,
                padding: EdgeInsets.symmetric(horizontal: 5),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Flexible(
                      child: Text(
                        gameName,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 14, fontWeight: FontWeight.w500),
                      ),
                    ),
                    Icon(
                      chooseType == 2
                          ? Icons.keyboard_arrow_up
                          : Icons.keyboard_arrow_down,
                      color: Color(0xff979797),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget chooseBody() {
    Widget content;
    if (chooseType == 1) {
      content = ListView.builder(
        itemBuilder: (ctx, i) {
          var index = i - 1;
          var showName = S.of(context).Venues2;
          if (index != -1) {
            var item = venueList[index];
            showName = item.name;
          }

          return GestureDetector(
              child: Container(
                height: 45,
                margin: EdgeInsets.symmetric(vertical: 5),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: index == tempSelected
                      ? ThemeColor.primaryColor
                      : Color(0xfff4f4f4),
                  borderRadius: BorderRadius.all(Radius.circular(4)),
                ),
                child: Text(
                  showName,
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 14),
                ),
              ),
              onTap: ClickUtils.debounce(
                () {
                  setState(() {
                    tempSelected = index;
                  });
                },
              ));
        },
        // separatorBuilder: (ctx, index) {
        //   return Container(
        //     height: 10,
        //   );
        // },
        itemCount: venueList.length + 1,
      );
    } else {
      List<Widget> children = [];
      for (int i = 0; i < gameList.length + 1; i++) {
        var index = i - 1;
        var showName = S.of(context).Sports3;
        if (index != -1) {
          var e = gameList[index];
          showName = e.discipline_name;
        }

        var item = GestureDetector(
            child: Container(
              height: 40,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: index == tempSelected
                    ? ThemeColor.primaryColor
                    : Color(0xfff4f4f4),
                borderRadius: BorderRadius.all(Radius.circular(4)),
              ),
              child: Text(
                showName,
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 14),
              ),
            ),
            onTap: ClickUtils.debounce(
              () {
                setState(() {
                  tempSelected = index;
                });
              },
            ));
        children.add(item);
      }
      content = GridView.count(
        crossAxisCount: 3,
        children: children,
        crossAxisSpacing: 7,
        mainAxisSpacing: 7,
        childAspectRatio: 3.2,
      );
    }

    return Column(
      children: [
        Container(
          height: 0.5,
          color: Color(0xffefefef),
        ),
        ClipRRect(
          borderRadius: BorderRadius.only(
            bottomLeft: Radius.circular(16),
            bottomRight: Radius.circular(16),
          ),
          child: Container(
            height: 320,
            padding: EdgeInsets.only(top: 0, left: 0, right: 0, bottom: 12),
            color: Colors.white,
            child: Column(
              children: [
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 15),
                    child: content,
                  ),
                ),
                Container(
                  height: 0.5,
                  color: ThemeColor.colorBlack10,
                ),
                Container(
                  padding: EdgeInsets.only(top: 12, left: 15, right: 15),
                  height: 52,
                  child: Row(
                    children: [
                      Expanded(
                        child: GestureDetector(
                          onTap: ClickUtils.debounce(() {
                            setState(() {
                              chooseType = 0;
                            });
                          }),
                          child: Container(
                            height: 40,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: Color(0xfff4f4f4),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8)),
                            ),
                            child: Text(
                              S.of(context).Cancel,
                              style: TextStyle(fontSize: 16),
                            ),
                          ),
                        ),
                      ),
                      Container(
                        width: 15,
                      ),
                      Expanded(
                        child: GestureDetector(
                          onTap: ClickUtils.debounce(() {
                            setState(() {
                              if (chooseType == 1) {
                                selectedVenue = tempSelected;
                              } else if (chooseType == 2) {
                                selectedGame = tempSelected;
                              }
                              chooseType = 0;
                            });
                            refreshData();
                          }),
                          child: Container(
                            height: 40,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: ThemeColor.primaryColor,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8)),
                            ),
                            child: Text(
                              S.of(context).confirm,
                              style: TextStyle(fontSize: 16),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ],
    );
  }

  void refreshData() {
    _tableController.reloadData();
  }

  Widget content() {
    return NormalTableView<GameVideoListItem>(
      controller: _tableController,
      getData: (page) async {
        gameList = await API.shared.game.items();
        venueList = await API.shared.venue.list();
        setState(() {});
        String? venue, game;
        try {
          venue = venueList[selectedVenue].code;
        } catch (e) {}
        try {
          game = gameList[selectedGame].id;
        } catch (e) {}
        return API.shared.game.gameVideoList(1, venue: venue, discipline: game);
      },
      enableLoadMore: false,
      padding: EdgeInsets.all(10),
      itemBuilder: (context, item) {
        return Column(
          children: [
            itemWidget(item),
            Container(
              height: 10,
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: needBar
          ? AppBar(
              title: Text(title),
            )
          : null,
      body: Column(
        children: [
          chooseBar(),
          Expanded(
            child: Stack(
              children: [
                content(),
                if (chooseType != 0)
                  Positioned.fill(
                    child: Container(
                      color: Colors.black.withOpacity(0.5),
                    ),
                  ),
                if (chooseType != 0) Positioned.fill(child: chooseBody()),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
